package com.example.my_self_view.calendar

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding

/**
 * @dsc     简介
 * @Author  LiWeiZhong
 * @Date    2025/2/28 10:11
 * @Version 1.0
 */
abstract class BaseAdapter<T, VB: ViewBinding>: RecyclerView.Adapter<BaseAdapter<T, VB>.ViewHolder>() {

    private var mData = arrayListOf<T>()

    abstract fun getB(inflater: LayoutInflater, parent: ViewGroup): VB

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return ViewHolder(getB(inflater, parent))
    }

    abstract fun bindHolder(holder: ViewHolder, position: Int)

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        bindHolder(holder, position)
    }

    override fun getItemCount(): Int {
        return mData.size
    }

    abstract fun addItemListener(holder: RecyclerView.ViewHolder)

    inner class ViewHolder(viewBinding: VB): RecyclerView.ViewHolder(viewBinding.root) {
        val mBinding = viewBinding

        init {
            addItemListener(this)
        }
    }

    fun getData() = mData
    fun setData(data: MutableList<T>) {
        val originLen = mData.size
        mData.clear()
        notifyItemRangeRemoved(0, originLen)
        mData.addAll(data)
        notifyItemRangeInserted(0, mData.size)
    }

    fun getData(position: Int) = mData[position]

    fun addData(data: MutableList<T>) {
        mData.addAll(data)
        notifyItemRangeInserted((mData.size - data.size), data.size)
    }
    fun addData(data: T?) {
        if (data == null) return
        mData.add(data)
        notifyItemInserted(mData.size - 1)
    }
    fun removeData(position: Int) {
        mData.removeAt(position)
        notifyItemRemoved(position)
        notifyItemRangeChanged(position, mData.size)
    }
    fun clear() {
        val originLen = mData.size
        mData.clear()
        notifyItemRangeRemoved(0, originLen)
    }


}